package
{
	import mx.automation.codec.AssetPropertyCodec;
	import mx.formatters.DateFormatter;
	import mx.rpc.mxml.Concurrency;
	import mx.utils.StringUtil;
	import flash.display.Loader;
	import flash.net.URLStream;
	import flash.net.URLLoader;
	import flash.events.Event;
	import flash.utils.setTimeout;
	import flash.net.URLVariables;
	
	public class WMFScrobbler
	{
		//import classes
		import mx.controls.Alert;
		import flash.net.URLRequest;
		import com.adobe.crypto.MD5;
		
		//Vars
		public var username:String;
		public var password:String;
		public var hsstatus:String;
		public var sessionid:String;
		public var loader:URLLoader=new URLLoader();
		public var trackloader:URLLoader=new URLLoader();
		public var handshakeurl:String;
		public var submiturl:String;
		
		//Methods
		//handshake
		public function handshake():void{
			var md5:MD5=new MD5();
			var md5pass:String;
			var authkey:String;
			var timestamp:String;
			var unixts:Date = new Date();
			timestamp=int((unixts.getTime()/1000)).toString();			
			authkey=md5.hash(md5.hash(StringUtil.trim(password))+timestamp);
			handshakeurl='http://post.audioscrobbler.com/?hs=true&p=1.2&c=tst&v=1.0&u='+username+'&t='+timestamp+'&a='+authkey+'';
			var geturl:URLRequest=new URLRequest(handshakeurl);
			loader.addEventListener(Event.COMPLETE,checkHSResult);
			loader.load(geturl);
		}
		
		//Get the results of the handshake
		public function checkHSResult(event:Event):void{
			var lines:Array=loader.data.split("\n");
			var i:int;
			for(i=0;i<lines.length;i++){
				hsstatus=lines[0].toString();
				sessionid=StringUtil.trim(lines[1].toString());
				submiturl=StringUtil.trim(lines[3].toString());
			}
		}
		
		//return status of handshake
		public function handshakeStatus():String{
			return hsstatus;
		}
		
		//Scrobble a track
		public static const POST:String = "POST"
		public function scrobbleThis(Artist:String, TrackName:String, TimeStamp:String, TrackLength:String, TrackNumber:String="", Album:String="" ):void{
			var trackurl:String=submiturl;
			var url:URLRequest=new URLRequest(trackurl);
			url.method="POST";
			var trackdata:String='s='+sessionid+'&a[0]='+Artist+'&t[0]='+TrackName+'&i[0]='+TimeStamp+'&o[0]=P&r[0]=L&l[0]='+TrackLength+'&b[0]='+Album+'&n[0]='+TrackNumber+'&m[0]=';
			url.data=trackdata;
			trackloader.load(url);
			trackloader.addEventListener(Event.COMPLETE,trackStatus);
		}
		
		public function trackStatus(event:Event):void{
			Alert.show('---'+trackloader.data+'---');
		}
		
	}
}